<script lang="ts" setup name="MapList">
import { reqGetFeatureByFeatureId, reqGetFeatureListTree1, reqGetFeatureListTree2 } from "@/api/feature";
import { requestGetData, requestIsSuccess } from "@/api/request";
import { Feature, Features } from "@/class/map/Feature"
import { successMessage, warningMessage } from "@/utils/message";
import { getShapeFile } from "@/utils/map";

// import AMapSingleView from "@/views/map/AMapSingleView.vue";
import { MapData } from "@/class/map/MapData";
import { Polygon, PolygonData } from "@/class/map/Polygon";
import { getRandomColor, getUUID } from "@/utils/utils";
import AMapView from "@/views/map/container/AMapView.vue";
import { Polyline, PolylineData } from "@/class/map/Polyline";
import { Marker, MarkerData } from "@/class/map/Marker";
import { reactive, ref, watch } from "vue";
import { MapCoordSys, MapType } from "@/class/map/myMapOpt";
import { FeatureDataInterface } from "@/class/map/MapData"
import { Delete as DeleteIcon, LocationFilled as LocationFilledIcon, Upload as UploadIcon } from "@element-plus/icons-vue";


const data = reactive([])
const props = reactive({
    label: 'name',
    children: 'zones'
})
//用户添加数据，选择属性
const select = reactive({
    show: false,
    //字段名
    fieldName: [],
    //属性表
    properties: [],
    //全选字段
    allSelect: '',
    //添加的数据,临时
    features: []
})
let map = null
let mapCoordSys = ref(MapCoordSys.CJ02)
let features = reactive<FeatureDataInterface[]>([])
let featuresIsUpload = reactive([])


function showUpload(index: number) {
    return featuresIsUpload[index] || false
}
/**
 * 通过id获取行政边界，并添加数据到数据库
 * @param id
 * @returns {Promise<void>}
 */
async function addFeature2MapById(id: string) {
    addFeature2Map(id)
}
/**
 * 获取数据并上传
 * @param id
 * @returns {Promise<boolean|void>}
 */
async function addFeature2Map(id: string) {
    const result = await reqGetFeatureByFeatureId(id);
    const data = result.data
    var feature = new Feature(data);
    var myMap = feature.getMyMap()
    const flag = await myMap.upload()
    if (flag) {
        successMessage("已保存" + myMap.featureData.name)
    }
}
function loadNode(node, resolve) {
    if (node.level === 0) {
        reqGetFeatureListTree1(node.level + 1, "").then(result => {
            const firstLevelList = result.data
            const config = []
            for (let i = 0; i < firstLevelList.length; i++) {
                let temp = firstLevelList[i]
                config[i] = { name: temp.featuresName, data: new Features(temp) }
            }
            resolve(config);

        })
    } else {
        reqGetFeatureListTree2(node.level + 1, node.data.data.id).then(result => {
            const featureList = result.data
            const config = []
            for (let i = 0; i < featureList.length; i++) {
                let temp = featureList[i]
                config[i] = { name: temp.name, data: new Feature(temp) }
            }
            resolve(config)
        })
    }
}
function handleCheckChange(data, checked, indeterminate) {
    console.log(data, checked, indeterminate);
}
function updateMap(domMap) {
    map = domMap
}
function updateCoordsy(coordsy) {
    mapCoordSys = coordsy
}

function addShapefile(event) {
    getShapeFile(event).then(features => {
        if (features) {
            if (!features[0].properties) {
                //属性表有误，随机生成ID
                warningMessage("文档属性表有误")
                select.properties = features.map(() => {
                    return { "random": getUUID() }
                })
                select.fieldName = ["random"]
            } else {
                //读取属性表
                select.properties = features.map(feature => feature.properties)
                select.fieldName = Object.keys(features[0].properties)
            }
            select.show = true;
            select.features = features
        } else {
            console.log("未选择对象")
            return;
        }
    })
}
function confirmNameSelection() {
    select.show = false;
    //default coordsys
    const coordsys = MapCoordSys.GPS
    features.splice(0, features.length)
    for (let i = 0; i < select.features.length; i++) {
        let feature = select.features[i];
        const { geometry: { type, coordinates }, properties } = feature
        let path = coordinates
        while (path.length === 1) {
            path = path[0]
        }
        let name = select.properties[i][select.allSelect] || getUUID()

        let item = null;
        if (name) {
            let mapData = undefined
            switch (type) {
                case MapType.Polygon:
                case "MultiPolygon"://todo 取消字符串
                    const polygon = new Polygon({
                        id: undefined,//自动生成uuid，防止重复上传，id一致
                        path,
                    });
                    mapData = new MapData({
                        id: getUUID(),//自动生成uuid，防止重复上传，id一致
                        type: MapType.Polygon,
                        name,
                        coordsys,
                    })
                    item = new PolygonData({ featureData: mapData, featureMap: polygon });
                    break;
                case MapType.Polyline:
                case "MultiLineString":
                case "LineString":
                    const polyline = new Polyline({
                        id: undefined,
                        path
                    });
                    mapData = new MapData({
                        id: getUUID(),//自动生成uuid，防止重复上传，id一致
                        type: MapType.Polyline,
                        name,
                        coordsys,
                    })
                    item = new PolylineData({ featureData: mapData, featureMap: polyline });
                    break;
                case MapType.Marker:
                    const marker = new Marker({
                        id: undefined,
                        position: path,
                    });
                    mapData = new MapData({
                        id: getUUID(),//自动生成uuid，防止重复上传，id一致
                        type: MapType.Marker,
                        name,
                        coordsys,
                    });
                    item = new MarkerData({ featureData: mapData, featureMap: marker })
            }
            if (item) {
                features.push(item);
                featuresIsUpload.push(false);
            } else {
                console.log("地图要素创建失败:", feature, "类型：", type)
            }
            // addFeature(data)
        }
    }
}
async function upload(item) {
    let flag = await item.upload();
    if (flag) {
        let index = features.findIndex(feature => {
            return feature.featureData.id === item.featureData.id
        })
        featuresIsUpload.splice(index, 1, true)
        item.getDateInMap(map).clearEvents("click");
        successMessage("添加成功")
    }
}
/**
 * 清除添加的地图数据
 */
function clear() {
    // $refs.fileInput.value = '';
    features.splice(0, features.length)
}
function deleteMapData(row) {
    // deleteFeature(row)
}

function moveTo(row) {
    row.blinkData(map)
    row.moveTo(map)
}

watch(features, (newVal) => {
    const intervalId = setInterval(() => {
        if (map !== null) {
            clearInterval(intervalId);

            const dataInMap = map.getAllOverlays();
            dataInMap.forEach(data => {
                let flag = newVal.findIndex(item => {
                    return item.featureData.id === data.getExtData().id
                })
                if (flag === -1) {
                    map.remove(data)
                }
            })
            newVal.forEach(item => {
                const flag = item.getDateInMap(map)
                if (!flag) {
                    const feature = item.addToMap(map, item.featureData.coordsys)
                    feature.on('click', () => {
                        upload(item)
                    })
                }
            })
        }
    }, 100);
})
function update2User(id: string) {
    console.log(id);
    reqGetFeatureByFeatureId(id).then(async (result) => {
        if (result.data) {
            let feature = new Feature(result.data);
            let item = feature.getMyMap();
            const flag = await item.upload();
            if (flag)
                successMessage("上传成功")
        }

    })
}
const highlightNode = (node) => {
    console.log(node.target.classList.push)
    node.target.classList.add('highlight-node');
}
const unhighlightNode = (node) => {
    node.target.classList.remove('highlight-node');
}
</script>
<template>
    <el-dialog v-model="select.show" title="选择名称属性" width="500">
        <el-table :data="select.properties" class="table-container" height="400px">
            <!-- 循环生成表头列 -->
            <el-table-column v-for="(field, colIndex) in select.fieldName" :label="field" :prop="123">
                <template #header>
                    <el-radio-group v-model="select.allSelect" :title="field">
                        <el-radio :label="field"></el-radio>
                    </el-radio-group>
                </template>
                <!-- 单元格内容 -->
                <template #default="scope" style="overflow-x: hidden">
                    <div @click="select.allSelect = field" :title="field">
                        <div v-if="select.allSelect === field">
                            {{ scope.row[field] }}
                        </div>
                        <div v-else>{{ (scope.row[field]) }}</div>
                    </div>
                </template>
            </el-table-column>

        </el-table>
        <template #footer>
            <el-button @click="select.show = false">取消</el-button>
            <el-button type="primary" @click="confirmNameSelection">确定</el-button>
        </template>
    </el-dialog>
    <div>
        <input type="file" multiple accept="*" v-on:change="addShapefile" placeholder="添加shapefile"
            ref="fileInput"></input>
        <template>

        </template>
        <el-button @click="clear">清除</el-button>
        <!--    <AMapSingleView></AMapSingleView>-->
        <div v-if="features.length > 0">
            <AMapView @updateMap="updateMap" @pdateCoordsy="updateCoordsy" :features="features"
                :can-change-layer="false">
            </AMapView>
            <el-table :data="features" style="width: 100%;margin-top: 10px">
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column label="数据" style='overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;'>
                    <template v-slot="{ $index, row }">
                        {{ row.featureData.name || "unknow name" }}<span v-if="row.featureData.top">&#9875;</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ $index, row }">
                        <el-button type="danger" @click="deleteMapData(row)" circle :icon="DeleteIcon"></el-button>
                        <el-button size="mini" @click="moveTo(row)" circle :icon="LocationFilledIcon"></el-button>
                        <el-button size="mini" @click="upload(row)" circle :icon="UploadIcon"
                            v-if="!showUpload($index)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-else>
            <el-tree :props="props" :load="loadNode" lazy @check-change="handleCheckChange" :data="data"
                :expand-on-click-node="false">
                <template #default="{ node, data }">
                    <div class="custom-tree-node" v-if='node.data.data instanceof Feature'
                        @mouseenter="highlightNode" @mouseleave="unhighlightNode">
                        <span>{{ node.label }}</span>
                        <div>
                            <el-button type="primary" @click="update2User(node.data.data.featureId)">update</el-button>
                        </div>
                    </div>
                </template>
            </el-tree>
        </div>
    </div>
</template>
<style scoped>
.table-container {
    height: 400px;
    /* 设置表格容器的固定高度 */
    overflow-y: auto;
    /* 允许垂直滚动 */
    overflow-x: visible;
    /* 允许垂直滚动 */
}

/* /deep/  */
div.el-table__body-wrapper {
    overflow: visible;
}

/* /deep/ */
div.el-table__header-wrapper {
    overflow: visible;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.table-container {
    height: 400px;
    /* 设置表格容器的固定高度 */
    overflow-y: auto;
    /* 允许垂直滚动 */
    overflow-x: visible;
    /* 允许垂直滚动 */
}

div.el-table__body-wrapper {
    overflow: visible;
}

div.el-table__header-wrapper {
    overflow: visible;
}

/* 定义高亮样式 */
.highlight-node {
    color: lightblue;
}
</style>